package com.zhilehuo.pretask.ui.library

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zhilehuo.pretask.adapter.Article
import com.zhilehuo.pretask.adapter.Category
import com.zhilehuo.pretask.repo.LibraryRepository
import kotlinx.coroutines.launch

/**
 * @Description: 文库数据ViewModel
 * @Author: Realnt
 * @Date:
 */
class LibraryViewModel : ViewModel() {

    private val repository = LibraryRepository()

    val categories = MutableLiveData<List<Category>>()
    val difficulties = MutableLiveData<List<Int>>()
    val articles = MutableLiveData<List<Article>>()
    val errorMessage = MutableLiveData<String>()
    val successMessage = MutableLiveData<String>()

    // 筛选条件
    var selectedTypeId = MutableLiveData(0)
    val selectedDifficulty = MutableLiveData(650)

    private var currentPage = 1
    private var totalPages = 1

    init {
        loadInitialData()
    }

    /**
     * @Description: 初始化
     * @Param  :
     * @Return  :
     */
    private fun loadInitialData() {
        loadCategories() // 加载分类
        loadDifficulties() // 加载难度
        loadArticles() // 加载文章
    }

    /**
     * @Description: 加载分类
     * @Param  :
     * @Return  :
     */
    private fun loadCategories() {
        viewModelScope.launch {
            try {
                val currentList = categories.value ?: emptyList() // 获取当前列表，如果为空则初始化为空列表
                val updatedList = currentList.toMutableList() // 将不可变列表转换为可变列表
                updatedList.addAll(0, repository.getCategories())
                updatedList.add(0, Category(0, "精选阅读")) // 将精选阅读添加到第一个位置
                categories.value = updatedList // 更新 MutableLiveData 的值
            } catch (e: Exception) {
                //errorMessage.value = "分类加载失败: ${e.message}"
            }
        }
    }

    /**
     * @Description: 加载难度
     * @Param  :
     * @Return  :
     */
    private fun loadDifficulties() {
        viewModelScope.launch {
            try {
                difficulties.value = repository.getDifficulties()
            } catch (e: Exception) {
                    errorMessage.value = "难度加载失败: ${e.message}"
            }
        }
    }

    /**
     * @Description: 加载文章
     * @Param isRefresh : 这次加载是否是刷新
     * @Return  :
     */
    fun loadArticles(isRefresh: Boolean = false) {
        viewModelScope.launch {
            try {
                val pageToLoad = if (isRefresh) 1 else currentPage
                val result = repository.getArticles(
                    lexile = selectedDifficulty.value ?: 0,
                    typeId = selectedTypeId.value ?: 0,
                    page = pageToLoad,
                    size = 10
                )

                if (isRefresh) {
                    currentPage = 1
                    articles.value = result.list // 更新文章列表
                } else {
                    val currentList = articles.value ?: emptyList()
                    articles.value = currentList + result.list // 合并新数据
                }

                currentPage = result.pageNum + 1
                totalPages = result.total

                successMessage.value = "请求成功: ${result.list.size}篇文章"

            } catch (e: Exception) {
                errorMessage.value = "加载失败: ${e.message}"
            }
        }
    }

    /**
     * @Description: 刷新文章
     * @Param  :
     * @Return  :
     */
    fun refreshArticles() {
        currentPage = 1
        loadArticles(isRefresh = true)
    }
}